package com.cloud.bc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpUtil;
import com.cloud.bc.config.AliOssConfig;
import com.cloud.bc.model.entity.BcSingles;
import com.cloud.bc.model.entity.CjVxiangqin;
import com.cloud.bc.mapper.CjVxiangqinMapper;
import com.cloud.bc.service.CjVxiangqinService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.oss.AliOssRequest;
import com.cloud.common.oss.AliOssResponse;
import com.cloud.common.oss.AliUploadHelper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.util.List;

/**
 * 采集微信相亲网
 *
 * @author douhaichao code generator
 * @date 2021-06-28 15:52:06
 */
@Service
@AllArgsConstructor
public class CjVxiangqinServiceImpl extends ServiceImpl<CjVxiangqinMapper, CjVxiangqin> implements CjVxiangqinService {
    private final AliOssConfig aliOssConfig;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public CjVxiangqin selectOne(CjVxiangqin req) {
        QueryWrapper queryWrapper = new QueryWrapper<CjVxiangqin>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<CjVxiangqin> selectAll(CjVxiangqin req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<CjVxiangqin> selectPage(Page page, CjVxiangqin req) {
        IPage<CjVxiangqin> list = baseMapper.selectPage(
                page,
                new QueryWrapper<CjVxiangqin>().setEntity(req));
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(CjVxiangqin req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public void main(Integer maxPage) {
        String mainUrl = "https://www.vxiangqin.com/p/user.php?form_mate_sex=2&t=1&p={index}";
        for (int i = 1; i <= maxPage; i++) {
            mainUrl = StrUtil.replace(mainUrl, "{index}", i + "");
            list(mainUrl);
        }
    }

    private void list(String url) {
        String listHtml = HttpUtil.get(url);
        List<String> listDetailUrl = ReUtil.findAllGroup1("<li><a href=\"(.*?)\" class=\"mbox\" target=\"_blank\">", listHtml);
        for (String detailUrl : listDetailUrl) {
            detail(detailUrl);
        }
    }

    private void detail(String url) {
        String detailHtml = HttpUtil.get(url);
        String headImg = ReUtil.get("<div class=\"uid\"><img src=\"(.*?)\" />", detailHtml, 1);
//        String headImgUrl = getHeadImgUrl(headImg);
        String trueName = getTrueName(detailHtml);
        String uid = ReUtil.get("（UID：(.*?)）", detailHtml, 1);
        String baseData = ReUtil.get(" <div class=\"udata\">([\\s\\S]+?)</div>", detailHtml, 1);
        List<String> listBaseData = ReUtil.findAllGroup1("<li>(.*?)</li>", baseData);

        //详细资料
        String detailInfo = ReUtil.get("<h1>详细资料</h1>([\\s\\S]+?)<div class=\"clear\"></div>", detailHtml, 1);
        String zeouInfo = ReUtil.get("<h1 class=\"brtop\">择偶要求</h1>([\\s\\S]+?)</div>", detailHtml, 1);
        convertSingle(listBaseData);
    }

    private void convertSingle(List<String> listBaseData) {
        BcSingles bcSingles = new BcSingles();
        //年龄
        String age = Convert.toStr(listBaseData.get(0));
        age = StrUtil.replace(age, "岁", "");
        age = 2021 - Convert.toInt(age) + "-01-01";
        bcSingles.setBirthday(Convert.toDate(age));
//婚姻状态
        String marriage = Convert.toStr(listBaseData.get(1));
        if (!StrUtil.isEmpty(marriage)) {
            bcSingles.setMarriageCn(marriage);
            if (marriage.equals("未婚")) {
                bcSingles.setMarriage(173);
            } else if (marriage.equals("离异")) {
                bcSingles.setMarriage(174);
            } else if (marriage.equals("丧偶")) {
                bcSingles.setMarriage(175);
            }
        }
        //身高
        String height = Convert.toStr(listBaseData.get(2));
        bcSingles.setHeight(StrUtil.isEmpty(height) ? 0 : Convert.toInt(StrUtil.replace(height, "cm", "")));
        initIncome(bcSingles, listBaseData);
    }

    private void initIncome(BcSingles bcSingles, List<String> listBaseData) {
        String income = Convert.toStr(listBaseData.get(2));
        if (StrUtil.isEmpty(income) || !income.contains("~")) {
            return;
        }
        String[] listIncome = StrUtil.split(income, "~");

        String incomeMin = listIncome[0];
        if (incomeMin.contains("千")){
            
        }
        String incomeMax = listIncome[1];

        if(incomeMax.contains("万"));
    }

    private String getTrueName(String detailHtml) {
        String trueName = ReUtil.get("<div class=\"uinfo\">([\\s\\S]+?)<font", detailHtml, 1);
        trueName = HtmlUtil.cleanHtmlTag(trueName);
        trueName = StrUtil.replace(trueName, " ", "");
        trueName = StrUtil.replace(trueName, "\r", "");
        trueName = StrUtil.replace(trueName, "\n", "");
        return trueName;
    }

    private String getHeadImgUrl(String headImg) {
        String uuid = UUID.randomUUID().toString();
        String localFilePath = "D:\\img\\" + uuid + ".jpg";
        File file = HttpUtil.downloadFileFromUrl(headImg, localFilePath);
        BufferedInputStream inputStream = FileUtil.getInputStream(file);
        AliOssRequest aliOssRequest = new AliOssRequest();
        BeanUtil.copyProperties(aliOssConfig, aliOssRequest);
        AliUploadHelper aliUploadHelper = new AliUploadHelper(aliOssRequest);
        String filePath = "single/" + uuid + ".jpg";
        AliOssResponse aliOssResponse =
                aliUploadHelper.uploadSimple(inputStream, filePath);
        String absolutePath = aliOssResponse.getAbsolutePath();
        return absolutePath;
    }
}
